import {
  indexApi
} from '../../api/index';
import {
  request
} from '../../utils/request';
import Dialog from '@vant/weapp/dialog/dialog';
const app = getApp();
Page({
  data: {
    programme: {},
    defaultData: {
      title: "方案报价", // 导航栏标题
      isBackToPreviousPage: false
    },
    three: true, //三图标
    tabs: 0, //选择的房间id
    keyword: '', // 用于存储用户输入的搜索关键词
    roomName: "",
    rotate: false, // 控制图片的旋转状态
    currentImageUrl: '/images/image-quick/dropDown.png', //下拉箭头
    showImageUrl: true,
    squareCheckedProducts: {},
    checkedAll: false, //全选状态
    menuList: [], //服务类目
    showpopup: false, //类目显示
    showAllocation: false, //显示配置
    sanPopup: false, //显示小弹框"三
    showRoomPopup: false, //显示房间弹框
    addressPop: false, //显示地址弹框
    selectedAddressId: "", //选中的地址id,
    selectedAddress: "", //选中的地址
    clickActionsMiddle: "",
    showTime: false, //日期显示
    selectedDate: '', //日期
    minDate: new Date().getTime(), //当前时间
    fileList: [], //图片上传
    serviceTypeName: null, //用户选择的类目
    serviceTypeId: null, //类目id
    inputValue: '',
    active: 0,
    isAllExpanded: false, // 用于记录是否全部展开
    isEdit: false, //用于记录是否编辑和完成
    orderId: null,
    isDelete: false,
    isCommodity: true,
    isSelectAll: false,
    isExpanded: false,
    isDialogVisible: false,
    currentProductId: null,
    tempProductCount: 0,
    isMerge: true,
    isSplit: true,
    position: false,
    stepper: true,
    productTypeNum: 0,
    productCount: 0,
    showInput: false,
    showPosition: false,
    show: false,
    tabsRoom: [],
    expandedProducts: {},
    productLocation: [],
    allLocation: [],
    MyLocations: [], // 私有位置列表
    PublicLocations: [], // 公共位置列表
    locationList: [],
    locationRadio: null,
    selectedLocation: '入门位置',
    locationId: null,
    ProductProperty: [],
    selectedProperty: '请选择',
    propertyId: null,
    pageNum: 1,
    pageSize: 12,
    Management: false,
    pgeName: "", //方案名称
    managementList: [], //方案数组
    managementRadio: null, // 当前选中的方案 ID
    isDel: 0,
    selectedManagement: {},
    managementName: "未设置方案",
    isSaveManagement: false,
    isUpdate: false,
    isEditModify: false,
    isAddManagement: false,
    isSaveAs: false,
    isDetail: false,
    isOpen: false,
    isOnSave: false,
    saveManagementID: null,
    nowManagement: {}, //当前方案
    defaultProgramme: {}, //默认方案
    managementTitleList: [], //方案的表头
    tabManagement: -1, //默认选中我的方案
    loading: false, // 控制loading的显示与隐藏
    error: null,
    dataerror: null,
    forwardShowPop: false, //转发弹框
    phoneNumber: null,
    workHours: 0,
    workPrice: 0,
    customPrice: null,
    customProductPrice: [],
    templateShow: false,
    templateList: [],
    selectedTemplateId: null,
    radio: "1",
    isForwardOrShare: null,
    isSubscribed: false, // 标志变量，表示是否已订阅
    SUBSCRIBE_TIMEOUT: 10000, // 设置时间间隔（例如：10秒）
  },

  onLoad(options) {
    this.getOneSeverAll()
    this.getDefaultHouseType()
    this.getSysConfigInfo()
    console.log("-------------------");
    // saveReportTemplateApi 保存用户报表模板
    //  delReportTemplateApi 删除用户报表模板
    // this.saveReportTemplate()
    // this.delReportTemplate()

    // this.getProgrammesByTypeId()

  },

  onShow() {
    const token = wx.getStorageSync('token');
    if (token) {
      this.getCustomPrice()
      Promise.all([this.getManagement(), this.getProgrammesByTypeIdForSimple()])
        .then(() => {
          if (Object.keys(this.data.selectedManagement).length <= 0) {
            this.defaultSelectedProgramme();
          }
        })
        .catch((err) => {
          console.error("Error in fetching data:", err);
        });
      if (app.globalData.importHouse == true) {
        this.getFromHouseType();
        app.globalData.importHouse = false
      }
      this.getLocationAll()

      this.getRoomAndProductAndAddress();
      console.log("=============");
    }

  },


  //选中第一个方案
  defaultSelectedProgramme() {
    console.log("选中第一个方案");
    if (this.data.managementList.length > 0) {
      this.setData({
        selectedManagement: this.data.managementList[0],
        managementRadio: this.data.managementList[0].id,
      })
      console.log("selectedManagement", this.data.selectedManagement);
    }
  },

  //保存方案
  showManagement() {
    if (this.data.isSaveManagement) {
      this.setData({
        Management: true,
        pgeName: "",
      });
    }

    if (this.data.isSaveAs) {
      this.setData({
        Management: true,
        pgeName: "",
      });
    }

    if (this.data.isEditModify) {
      this.setData({
        Management: true,
        pgeName: this.data.selectedManagement.pgeName,
      });
    }
    if (this.data.isAddManagement && !this.data.isSaveManagement) {
      this.setData({
        Management: true,
        pgeName: "",
      });
    }
  },

  // 编辑方案
  managementModify(event) {
    this.setData({
      isEditModify: true,
      selectedManagement: event.currentTarget.dataset.item,
    });
    this.showManagement();
  },

  // 输入方案名称
  pgeNameChange(event) {
    this.setData({
      pgeName: event.detail,
    });
  },

  // 确认方案名
  onConfirmAddRoom() {
    const pgeName = this.data.pgeName;
    const isDuplicate = this.data.managementList.some((item) => item.pgeName === pgeName);
    if (isDuplicate) {
      wx.showToast({
        title: '方案名称已存在',
        icon: 'none',
      });
      return;
    }
    if (!pgeName.trim()) {
      wx.showToast({
        title: '方案名称不能为空',
        icon: 'none',
      });
      return;
    }

    let updatedProgramme = {
      ...this.data.programme
    };
    let updatedSelectedManagement = {
      ...this.data.selectedManagement
    };

    //保存
    if (this.data.isSaveManagement) {
      updatedProgramme.pgeName = pgeName;
      this.newSubscribeSend().then(() => {
        this.saveTemplate(updatedProgramme);
      }).catch((error) => {
        this.saveTemplate(updatedProgramme);
        console.error('订阅消息失败:', error);
      });
    }
    //新增方案的保存
    if (this.data.isAddManagement && !this.data.isSaveManagement) {
      const defaultProgramme = this.data.defaultProgramme;
      defaultProgramme.pgeName = pgeName;
      updatedProgramme = defaultProgramme;
      this.setData({
        isAddManagement: true,
        isUpdate: false
      });
      this.saveTemplate(updatedProgramme);

      // this.newSubscribeSend().then(() => {
      //   this.saveTemplate(updatedProgramme);
      // }).catch((error) => {

      //   console.error('订阅消息失败:', error);
      // });

    }

    // 另存
    if (this.data.isSaveAs) {
      updatedProgramme.pgeName = pgeName;
      delete updatedProgramme.id;
      updatedProgramme.roomEntityList.forEach(room => {
        delete room.id;
        delete room.pgeId;
        if (room.roomProductEntityList && room.roomProductEntityList.length > 0) {
          room.roomProductEntityList.forEach(product => {
            delete product.id;
            delete product.pgeRoomId;
          });
        }
      });
      this.saveTemplate(updatedProgramme);
    }

    // 编辑
    if (this.data.isEditModify) {
      updatedSelectedManagement.pgeName = pgeName;

      this.saveTemplate(updatedSelectedManagement);
    }
    this.ManagementClose();
  },

  // 取消方案操作
  onCancelClose() {
    this.setData({
      Management: false,
      pgeName: "",
      isEditModify: false,
      isAddManagement: false,
      isSaveAs: false,
      isDetail: false,
      isOpen: false,
      isOnSave: false,
    });
  },
  // 关闭方案弹框
  ManagementClose() {
    this.setData({
      Management: false,
      pgeName: "",
    });
  },


  // 转发方案
  forward(event) {
    console.log("s是不是共享", event);
    this.setData({
      forwardShowPop: true,
      pgeName: this.data.selectedManagement.pgeName,
      phoneNumber: null,
      isForwardOrShare: event.currentTarget.dataset.type
    })
  },
  onPhoneNumberChange(event) {
    this.setData({
      phoneNumber: event.detail,
      // isPhoneNumberInvalid: false // 清除错误提示
    });
  },

  onConfirmForward() {
    const {
      phoneNumber
    } = this.data;


    // 正则校验中国大陆手机号格式
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(phoneNumber)) {
      this.setData({
        isPhoneNumberInvalid: true
      });
      wx.showToast({
        title: "请输入正确的手机号",
        icon: "none",
      });
      return;
    }
    if (this.data.isForwardOrShare == "forward") {
      this.forwardProgramme(phoneNumber);
    } else {
      this.shareTogetherProgramme(phoneNumber);
    }

    this.setData({
      forwardShowPop: false
    });
  },


  async shareTogetherProgramme(phoneNumber) {
    const {
      programme,
      selectedManagement
    } = this.data
    console.log("selectedManagement", selectedManagement);

    const reqSearch = {
      id: selectedManagement.id,
      phone: phoneNumber
    }
    try {
      const res = await request({
        url: indexApi.shareTogetherProgrammeApi(),
        method: "POST",
        data: reqSearch
      });

      if (res.code == 200) {
        wx.showToast({
          title: "共享成功",
          icon: "none",
        });
        console.log("共享成功", res.data);
        this.getManagement();
        this.getProgrammesByTypeId()
      }
      if (res.code == 301) {
        wx.showToast({
          title: "分享的用户不存在",
          icon: "none",
        });
      }


    } catch (error) {
      console.error("Error:", error);
    }
  },

  //共享方案
  shareTogether(event) {
    console.log("s是不是共享", event);
    this.setData({
      forwardShowPop: true,
      pgeName: this.data.selectedManagement.pgeName,
      phoneNumber: null
    })
  },

  async forwardProgramme(phoneNumber) {
    const {
      programme,
      selectedManagement
    } = this.data
    console.log("selectedManagement", selectedManagement);

    const reqSearch = {
      id: selectedManagement.id,
      phone: phoneNumber
    }
    try {
      const res = await request({
        url: indexApi.forwardProgrammeApi(),
        method: "POST",
        data: reqSearch
      });

      if (res.code == 200) {
        wx.showToast({
          title: "转发成功",
          icon: "none",
        });
      }
      console.log("转发", res.data);
      this.getManagement();
      this.getProgrammesByTypeId()

    } catch (error) {
      console.error("Error:", error);
    }
  },


  // 保存方案
  showManagementPop() {
    if (this.data.isUpdate == false) {
      this.setData({
        isSaveManagement: true
      })
      this.showManagement(this.data.programme)
    } else {
      wx.showToast({
        title: "正在更新",
        icon: "none",
      });
      this.saveTemplate(this.data.programme)
    }
  },

  // 另存方案
  saveAs() {
    this.setData({
      isSaveAs: true,
    })
    this.showManagement();
  },

  // 新增方案
  addManagement() {
    Dialog.confirm({
        title: '是否保存当前方案?',
        message: '如果不保存，您将创建一个新的初始化方案。',
        confirmButtonText: '保存',
        cancelButtonText: '不保存',
      })
      .then(() => {
        if (this.data.programme.id) {
          this.setData({
            isUpdate: true,
            isAddManagement: true,
            isOnSave: false,
          })
        } else {
          this.setData({
            isSaveManagement: true,
            isAddManagement: true
          })
        }
        this.showManagementPop();
      })
      .catch(() => {
        this.setData({
          Management: true,
          isAddManagement: true,
          pgeName: "",
        })
        return
      });
  },


  // 选中方案
  managementChange(event) {
    const {
      selectedManagement
    } = this.data
    this.setData({
      managementRadio: event.detail,
      selectedManagement: event.currentTarget.dataset.managementitem
    });
    console.log("选择方案", this.data.selectedManagement);
  },

  //打开方案
  openManagement() {
    const {
      selectedManagement
    } = this.data;
    const generateUniquePid = () => `${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    console.log("selectedManagement", selectedManagement);
    const nowManagement = selectedManagement.roomEntityList.map((item, index) => {
      const updatedItem = {
        ...item,
        tid: item.id,
      };
      const mergedProducts = updatedItem.roomProductEntityList.reduce((acc, product) => {
        const existingProduct = acc.find((p) => p.productId === product.productId);
        if (existingProduct) {
          existingProduct.count += product.count;
        } else {
          acc.push({
            ...product,
            pid: generateUniquePid()
          });
        }
        return acc;
      }, []);
      updatedItem.roomProductList = mergedProducts;
      updatedItem.roomProductEntityList = updatedItem.roomProductEntityList.map((product, index) => ({
        ...product,
        splitIndex: index,
        isDel: 0,
        isShow: 1,
        pid: generateUniquePid()
      }));
      if (index === 0) {
        for (let i = 0; i < 20 && i < updatedItem.roomProductEntityList.length; i++) {
          updatedItem.roomProductEntityList[i].isShow = 0;
        }
      }
      const uniqueProductIds = new Set(updatedItem.roomProductEntityList.map(product => product.productId));
      updatedItem.productTypeNum = uniqueProductIds.size;
      updatedItem.productCount = updatedItem.roomProductEntityList.reduce((total, product) => total + product.count, 0);
      return updatedItem;
    });
    console.log("nowManagement", nowManagement);
    const firstRoomId = nowManagement[0].tid;
    selectedManagement.roomEntityList = nowManagement;
    this.setData({
      isUpdate: true,
      programme: selectedManagement,
      tabs: firstRoomId,
      isSaveManagement: false,
      isEditModify: false,
      isAddManagement: false,
      isSaveAs: false,
      isDetail: false,
      // isMerge: false,
    });
    this.productLocationSort(this.data.programme.roomEntityList[0].roomProductEntityList);
    // this.toggleMergeSplit();
    console.log("方案", this.data.programme);
    app.globalData.programme = this.data.programme;
    wx.showToast({
      title: "方案打开成功",
      icon: "none",
    });
    this.productTotalQuantity()
    this.defaultProductState()
    this.addProgrammeData()
  },

  // 打开方案接口
  async getVoProgrammeById() {
    console.log("打开方案");
    const id = this.data.selectedManagement.id
    try {
      const res = await request({
        url: indexApi.getVoProgrammeByIdApi(id),
        data: {}
      });

      console.log("打开方案", res);
      this.setData({
        selectedManagement: res.data
      })
      this.openManagement()
    } catch (error) {
      console.error("Error:", error);
    }
  },

  // 方案添加数据
  addProgrammeData() {
    const {
      programme
    } = this.data
    programme.roomEntityList.forEach(room => {
      room.roomProductEntityList.forEach(product => {
        product.oldProductPrice = Number(product.product.productPrice)
        product.oldInstallationPrice = Number(product.product.installationPrice)
        product.oldServiceFee = Number(product.product.serviceFee)
        product.oldDebuggingPrice = Number(product.product.debuggingPrice)

      })
    })

    this.setData({
      programme
    })
    console.log(" 方案添加数据", this.data.programme);

  },


  //点击打开方案，询问客户
  openProgramme() {
    const {
      selectedManagement,
      programme
    } = this.data
    console.log("有没有选择方案", selectedManagement);
    console.log("有没有方案", programme);
    if (Object.keys(selectedManagement).length === 0 && selectedManagement.constructor === Object) {
      wx.showToast({
        title: "请选择一个方案",
        icon: "none",
      });
      return;
    }
    if (selectedManagement && programme && selectedManagement.id === programme.id) {
      wx.showToast({
        title: "此方案已打开",
        icon: "none",
      });
      return;
    }
    this.getSysConfigInfo()
    Dialog.confirm({
        title: '是否保存当前方案?',
        message: '如果不保存，您将打开一个新的方案。',
        confirmButtonText: '保存',
        cancelButtonText: '不保存',
      })
      .then(() => {
        if (this.data.programme.id) {
          this.setData({
            isOnSave: false,
            isSaveManagement: false,
            isUpdate: true,
            isEditModify: false,
            isAddManagement: false,
            isSaveAs: false,
            isDetail: false,
            isOpen: true,
            isOnSave: false,
          })
        } else {
          this.setData({
            isOnSave: false,
            isSaveManagement: true,
            isUpdate: false,
            isEditModify: false,
            isAddManagement: false,
            isSaveAs: false,
            isDetail: false,
            isOpen: true,
            isOnSave: false,
          })
        }
        this.showManagementPop();
      })
      .catch(() => {
        // this.openManagement()
        this.getVoProgrammeById()
      });
  },

  // 展示方案
  showProgramme() {
    const {
      programme
    } = this.data;
    const generateUniquePid = () => `${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    const nowManagement = programme.roomEntityList.map((item, index) => {
      const updatedItem = {
        ...item,
        tid: item.id,
      };
      const mergedProducts = updatedItem.roomProductEntityList.reduce((acc, product) => {
        const existingProduct = acc.find((p) => p.productId === product.productId);
        if (existingProduct) {
          existingProduct.count += product.count;
        } else {
          acc.push({
            ...product,
            pid: generateUniquePid()
          });
        }
        return acc;
      }, []);
      updatedItem.roomProductList = mergedProducts;
      updatedItem.roomProductEntityList = updatedItem.roomProductEntityList.map((product, index) => ({
        ...product,
        splitIndex: index,
        isDel: 0,
        pid: generateUniquePid()
      }));
      if (index === 0) {
        for (let i = 0; i < 20 && i < updatedItem.roomProductEntityList.length; i++) {
          updatedItem.roomProductEntityList[i].isShow = 0;
        }
      }
      const uniqueProductIds = new Set(updatedItem.roomProductEntityList.map(product => product.productId));
      updatedItem.productTypeNum = uniqueProductIds.size;
      updatedItem.productCount = updatedItem.roomProductEntityList.reduce((total, product) => total + product.count, 0);
      return updatedItem;
    });
    const firstRoomId = nowManagement[0].tid;
    programme.roomEntityList = nowManagement;
    if (this.data.isUpdate) {
      this.setData({
        isUpdate: true
      });
    }
    if (this.data.isSaveManagement) {
      this.setData({
        isSaveManagement: false,
        isUpdate: true
      });
    }
    if (this.data.isAddManagement) {
      this.setData({
        isAddManagement: false,
        isUpdate: true
      });
    }
    this.setData({
      programme: programme,
      selectedManagement: programme,
      tabs: firstRoomId,
      // isMerge: false,
    });
    // this.toggleMergeSplit();
    app.globalData.programme = this.data.programme;
    this.productLocationSort(this.data.programme.roomEntityList[0].roomProductEntityList);
    this.productTotalQuantity()
    this.defaultProductState()
    this.addProgrammeData()
  },


  // 删除方案
  deleteItem() {
    const {
      managementList,
      managementRadio,
      selectedManagement,
      programme
    } = this.data;
    if (managementRadio !== null) {
      Dialog.confirm({
          title: '确定要删除此方案吗？',
        })
        .then(() => {
          const newProgrammeEntity = selectedManagement
          const isDel = 1;
          newProgrammeEntity.isDel = isDel;
          this.setData({
            isDetail: true,
            // selectedManagement: newProgrammeEntity
          });
          if (selectedManagement.isShare == 1) {
            this.delShareRecordById()
          } else {
            this.saveTemplate(newProgrammeEntity);
          }
        })
        .catch(() => {});
    } else {
      wx.showToast({
        title: "请先选择一个方案",
        icon: "none",
      });
    }
  },

  // 删除共享方案
  async delShareRecordById() {
    console.log("删除共享方案");
    const id = this.data.selectedManagement.id
    try {
      const res = await request({
        url: indexApi.delShareRecordByIdApi(),
        method: "POST",
        data: {
          id
        }
      });

      console.log("删除共享", res);
    } catch (error) {
      console.error("Error:", error);
    }
  },

  // 保存方案
  async saveTemplate(newProgrammeEntity) {
    let {
      programme
    } = this.data;
    console.log("保存方案", this.data.programme);
    if (newProgrammeEntity) {
      programme = newProgrammeEntity;
    }
    console.log("programme", programme);
    try {
      const res = await request({
        url: indexApi.saveOrUpdateProgrammesApi(),
        method: "POST",
        data: programme,
      });
      console.log("方案接口打印", res.data);
      res.data.roomEntityList = this.transforDataTid(res.data.roomEntityList);
      if (this.data.isAddManagement && !this.data.isSaveManagement && !this.data.isUpdate) {
        wx.showToast({
          title: "添加成功",
          icon: "none",
        });
        this.setData({
          programme: res.data,
          selectedManagement: res.data,
          managementRadio: res.data.id,
          // isAddManagement: false,
        });
        this.showProgramme();
        this.getManagement();
        this.getProgrammesByTypeId()
        return
      }

      // 更新
      if (this.data.isUpdate && !this.data.isOnSave) {
        if (!this.data.isDetail && !this.data.isEditModify && !this.data.isSaveAs) {
          wx.showToast({
            title: "更新成功",
            icon: "none",
          });
          if (this.data.isAddManagement || this.data.isOpen) {
            if (this.data.isAddManagement) {
              this.setData({
                Management: true,
                pgeName: "",
                isUpdate: false
              })
            }
            if (this.data.isOpen) {
              this.setData({
                isOpen: false,
                isUpdate: false
              })
              // this.openManagement()
              this.getVoProgrammeById()
            }
          } else {
            this.setData({
              programme: res.data,
              selectedManagement: res.data,
              managementRadio: res.data.id,
            })
            this.showProgramme();
          }
        }
      }
      // 保存
      if (this.data.isSaveManagement) {
        wx.showToast({
          title: "保存成功",
          icon: "none",
        });

        if (this.data.isAddManagement || this.data.isOpen) {
          if (this.data.isAddManagement) {
            this.setData({
              isSaveManagement: false
            }, () => {
              setTimeout(() => {
                this.showManagement();
              }, 300);
            });
          }
          if (this.data.isOpen) {
            this.setData({
              isOpen: false,
              isSaveManagement: false
            })
            // this.openManagement()
            this.getVoProgrammeById()

          }
        } else {
          this.setData({
            programme: res.data,
            selectedManagement: res.data,
            managementRadio: res.data.id,
          })
          this.showProgramme();
        }

      }

      if (this.data.isSaveAs) {
        wx.showToast({
          title: "另存成功",
          icon: "none",
        });
        this.setData({
          programme: res.data,
          selectedManagement: res.data,
          managementRadio: res.data.id,
          isSaveAs: false,
        });
        this.showProgramme();
      }
      if (this.data.isDetail) {
        wx.showToast({
          title: "删除成功",
          icon: "none",
        });
        this.setData({
          isDetail: false,
        });
        if (this.data.programme.id == res.data.id) {
          const firstRoomId = this.data.defaultProgramme.roomEntityList[0].tid
          this.setData({
            programme: this.data.defaultProgramme,
            tabs: firstRoomId
          })
        }
      }
      if (this.data.isEditModify) {
        wx.showToast({
          title: "更名成功",
          icon: "none",
        });
        this.setData({
          isEditModify: false,
        });
      }
      this.getManagement();
      this.getProgrammesByTypeId()
    } catch (error) {
      console.error("Error:", error);
    }
  },

  transforDataTid(val) {
    val?.forEach(item => {
      item.tid = item.id
      item.roomProductEntityList?.forEach(function (a, b) {
        a.splitIndex = b;
      })
    })
    return val;
  },

  // 消息的订阅与推送
  newSubscribe() {
    const that = this;
    console.log("消息的订阅");

    // 如果已经订阅过，则不再执行
    if (that.isSubscribed) {
      console.log("已经订阅，稍后再试");
      return;
    }

    wx.requestSubscribeMessage({
      tmplIds: ['a7V3EulL0oPv_-0h3DvuSLDdd4HJwzhyxObqcnXc9MQ'],
      success(res) {
        if (res['a7V3EulL0oPv_-0h3DvuSLDdd4HJwzhyxObqcnXc9MQ'] === 'accept') {
          console.log('用户已同意订阅消息');
          that.testMessage();

          // 设定已订阅标志，并设置超时
          that.isSubscribed = true;
          setTimeout(() => {
            that.isSubscribed = false; // 超过时间后重置标志
          }, that.SUBSCRIBE_TIMEOUT);
        } else {
          console.log('用户拒绝订阅消息');
        }
      },
      fail(err) {
        console.error('订阅消息失败', err);
      }
    });
  },

  async testMessage() {
    try {
      const miniprogramState = __wxConfig.envVersion || 'trial';
      console.log("当前 miniprogramState:", miniprogramState);
      const res = await request({
        url: indexApi.testMessageApi(),
        method: "POST",
        data: {
          page: "pages/home/index",
          miniprogram_state: miniprogramState
        }
      });
      console.log("消息", res);
    } catch (error) {
      console.error("Error:", error);
    }
  },



  //获取方案管理名称
  async getManagement() {
    const reqSearch = {
      pageNum: this.data.pageNum,
      pageSize: this.data.pageSize
    }
    try {
      const res = await request({
        url: indexApi.getProgrammeTypeAllApi(),
        method: "POST",
        data: reqSearch
      });
      this.setData({
        managementTitleList: res.data.records
      })
      console.log("managementTitleList", this.data.managementTitleList);
    } catch (error) {
      console.error("Error:", error);
    }
  },

  async getProgrammesByTypeIdForSimple() {
    const reqSearch = {
      pageNum: this.data.pageNum,
      pageSize: this.data.pageSize,
      id: this.data.tabManagement
    }
    try {
      const res = await request({
        url: indexApi.getProgrammesByTypeIdForSimpleApi(),
        method: "POST",
        data: reqSearch
      });
      this.setData({
        managementList: res.data
      })

      console.log("managementList", this.data.managementList);
    } catch (error) {
      console.error("Error:", error);
    }
  },

  //预览方案
  previewProgramme() {
    this.setData({
      templateShow: true
    })

    this.getReportTemplatesByUser()
  },

  //获取模板列表
  async getReportTemplatesByUser() {
    const pageNum = 1;
    const pageSize = 1000;
    try {
      const res = await request({
        url: indexApi.getReportTemplatesByUserApi(pageNum, pageSize),
        data: {}
      });

      this.setData({
        templateList: res.data.records
      })

      console.log("获取模板列表", this.data.templateList);
    } catch (error) {
      console.error("Error:", error);
    }
  },

  onChange(event) {
    this.setData({
      radio: event.detail,
    });
  },

  // 确认选择模板
  onConfirmTemplate() {
    const selectedTemplateType = this.data.radio;
    let selectedTemplateId = null;
    console.log("selectedTemplateType", selectedTemplateType);
    if (selectedTemplateType == 2) {
      const defaultTemplate = this.data.templateList.find(template => template.isDefault == 1);
      if (defaultTemplate) {
        selectedTemplateId = defaultTemplate.id;
      } else if (this.data.templateList.length > 0) {
        selectedTemplateId = this.data.templateList[0].id;
      }
    }
    this.setData({
      selectedTemplateId: selectedTemplateId
    });

    // 调用下载方法
    this.downloadProgramme();
  },


  // 下载方案
  async downloadProgramme() {
    const reqTemplate = {
      id: this.data.selectedManagement.id,
      isNew: 1
    };
    console.log("this.data.selectedTemplateId", this.data.selectedTemplateId);
    if (this.data.selectedTemplateId !== null) {

      reqTemplate.reportCfgId = this.data.selectedTemplateId;
    }
    console.log("reqTemplate", reqTemplate);
    try {
      this.setData({
        loading: true,
        error: null
      });
      const res = await request({
        url: indexApi.reportPdfApi(),
        method: "POST",
        data: reqTemplate
      });
      this.setData({
        dataerror: res.data
      })
      wx.downloadFile({
        url: res.data,
        success: (downloadRes) => {
          if (downloadRes.statusCode === 200) {
            wx.openDocument({
              showMenu: true,
              filePath: downloadRes.tempFilePath,
              fileType: 'pdf',
              success: (openRes) => {
                this.setData({
                  loading: false,
                  selectedTemplateId: null
                });
              },
              fail: (openError) => {
                this.setData({
                  loading: false,
                  error: `文件打开失败: ${openError.errMsg}`
                });
                wx.showToast({
                  title: "文件打开失败",
                  icon: "none",
                });
              }
            });
          } else {
            this.setData({
              loading: false,
              error: `文件下载失败: ${downloadRes.errMsg}`
            });
            wx.showToast({
              title: "文件下载失败",
              icon: "none",
            });
          }
        },
        fail: (downloadError) => {
          wx.showToast({
            title: "下载文件失败",
            icon: "none",
          });
        }
      });

    } catch (error) {
      console.error("Error:", error);
      this.setData({
        loading: false,
        error: `请求失败: ${error.message}`
      });
      wx.showToast({
        title: "请求失败",
        icon: "none",
      });
    }
  },

  //分享方案
  async shareProgramme() {
    const id = this.data.selectedManagement.id;
    try {
      const res = await request({
        url: indexApi.shareProgrammeByIdApi(id),
        data: {}
      });
      // console.log("res", res.data);
      if (res.data) {
        wx.previewImage({
          urls: [res.data],
          current: res.data
        });
      } else {
        wx.showToast({
          title: '未获取到二维码链接',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error("Error:", error);
      wx.showToast({
        title: '请求失败',
        icon: 'none'
      });
    }
  },

  // saveReportTemplateApi 保存用户报表模板
  //  delReportTemplateApi 删除用户报表模板
  // async saveReportTemplate() {
  //   try {
  //     const res = await request({
  //       url: indexApi.saveReportTemplateApi(),
  //       method: "POST",
  //       data: reqSearch
  //     });
  //     console.log("保存用户报表模板", res);
  //   } catch (error) {
  //     console.error("Error:", error);
  //   }
  // },

  // async delReportTemplate() {
  //   try {
  //     const res = await request({
  //       url: indexApi.delReportTemplateApi(),
  //       method: "POST",
  //       data: reqSearch
  //     });
  //     console.log("删除用户报表模板", res);
  //   } catch (error) {
  //     console.error("Error:", error);
  //   }
  // },



  tabManagementTitle(event) {
    this.setData({
      tabManagement: event.currentTarget.dataset.id
    })
    console.log("点击的是哪一类型的方案", this.data.tabManagement);
    // this.getProgrammesByTypeId()
    this.getProgrammesByTypeIdForSimple()
  },


  async getProgrammesByTypeId() {
    const reqSearch = {
      pageNum: this.data.pageNum,
      pageSize: this.data.pageSize,
      id: this.data.tabManagement
    }
    try {
      const res = await request({
        url: indexApi.getProgrammesByTypeIdApi(),
        method: "POST",
        data: reqSearch
      });
      this.setData({
        managementList: res.data
      })

      console.log("managementList", this.data.managementList);
    } catch (error) {
      console.error("Error:", error);
    }
  },

  //发布订单
  async releaseOrders() {
    let {
      serviceTypeId,
      selectedAddressId,
      tabsRoom,
      selectedDate
    } = this.data;
    const allGoodsEmpty = tabsRoom.every(room => room.goods.length == 0);
    if (allGoodsEmpty) {
      Toast('请新增商品');
      return;
    }
    if (!selectedDate) {
      Toast('请先选择预约时间');
      return
    }
    if (!selectedAddressId) {
      Toast('请先选择地址');
      return
    }
    const transformedData = tabsRoom.map(room => {
      return {
        roomName: room.roomName,
        children: room.goods.map(product => {
          return {
            productId: product.productId,
            productName: product.productName,
            count: product.count,
            skillsVo: [{}],
            locationId: this.data.locationId,
            propertyId: this.data.propertyId
          };
        })
      };
    });
    const requestData = {
      addressId: selectedAddressId,
      service_time: selectedDate,
      children: transformedData,
    };

    try {
      const res = await request({
        url: indexApi.releaseOrdersApi(serviceTypeId),
        method: "POST",
        data: requestData
      });
      this.setData({
        order: res.data.orderId
      })
      const orderId = res.data.orderId
      this.getOrderByOrder(orderId)
    } catch (error) {
      console.error("Error:", error);
    }
  },

  // 初始化房间数据和产品列表
  async getDefaultHouseType() {
    try {
      const res = await request({
        url: indexApi.getDefaultHouseTypeApi(),
        data: {}
      });
      console.log("默认户型接口", res.data);

      // 处理房间数据
      const processedRooms = res.data.rooms.map(({
        id,
        ...rest
      }) => ({
        ...rest,
        tid: id,
        productCount: 0,
        productTypeNum: 0,
        roomProductEntityList: [],
        roomProductList: []
      }));

      console.log("processedRooms", processedRooms);

      // 初始化 programme 对象
      const initProgramme = (data) => ({
        roomEntityList: processedRooms,
        houseName: data.houseName,
        imgUrl: data.imgUrl,
        remark: data.remark,
        houseTypeItemId: data.id,
        productCount: 0,
        productTypeNum: 0,
        totalPrice: 0,
        debugPrice: 0,
        servicePrice: 0,
        programmeTotalPrice: 0,
        serviceDuration: 0,
        serviceFee: 0,
        priceModel: 1,
        priceDiscountPdt: null,
        priceDiscountSev: null,
        priceDiscountProduct: {},
        priceDiscountService: {}
      });

      const programme = initProgramme(res.data);

      this.setData({
        tabs: processedRooms[0]?.tid || '',
        programme: JSON.parse(JSON.stringify(programme)),
        defaultProgramme: JSON.parse(JSON.stringify(programme)),
      });

      this.defaultProductState();
      console.log("programme", this.data.programme);

    } catch (error) {
      console.error("Error:", error);
    }
  },

  // 获取导入的房间
  getFromHouseType() {
    console.log("==++++++++++++");
    const programme = app.globalData.programme;
    const firstRoom = programme.roomEntityList.find(room => room.isDel !== 1);
    const firstRoomId = firstRoom ? firstRoom.tid : null;
    this.setData({
      programme: programme,
      tabs: firstRoomId
    });
    console.log("获取导入的房间", this.data.programme);
    // if (programme.priceDiscountPdt !== null || programme.priceDiscountSev !== null) {
    //   console.log("===========");
    this.updateDiscounts()
    // }
  },

  // 更新房间下面的商品
  getRoomAndProductAndAddress() {
    const app = getApp();
    let selectedProducts = app.globalData.selectedProducts || [];
    const roomList = app.globalData.roomList || [];

    if (roomList.selectedAddress) {
      this.setData({
        "programme.addressId": roomList.selectedAddress.addressId
      });
    }
    const {
      programme
    } = this.data;
    if (selectedProducts.length > 0) {
      const generateUniquePid = () => `${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
      programme.roomEntityList.forEach(room => {
        if (room.tid === this.data.tabs) {
          selectedProducts.forEach(product => {
            let existingProduct = room.roomProductList.find(p => p.productId === product.productId);
            const splitAndAddProduct = (product, count) => {
              for (let i = 0; i < count; i++) {
                const splitProduct = {
                  ...product,
                  count: 1,
                  pid: generateUniquePid(),
                };
                room.roomProductEntityList.push(splitProduct);
              }
            };

            if (existingProduct) {
              existingProduct.count += product.count;
              splitAndAddProduct(product, product.count);
            } else {
              room.roomProductList.push({
                ...product,
                pid: generateUniquePid()
              });
              splitAndAddProduct(product, product.count);
            }
          });

          // 更新房间的商品实体信息
          room.roomProductEntityList.forEach((product, index) => {
            if (!product.id) {
              product.isDel = 0;
              product.isShow = 1;
              product.splitIndex = index;
              // product.oldProductPrice = Number(product.productPrice);
              // product.oldDebuggingPrice = Number(product.debuggingPrice);
              // product.oldInstallationPrice = Number(product.installationPrice);
              // product.oldServiceFee = Number(product.serviceFee);
            }
          });

          // 隐藏前20个商品
          for (let i = 0; i < Math.min(20, room.roomProductEntityList.length); i++) {
            room.roomProductEntityList[i].isShow = 0;
          }

          // 计算商品种类数量
          const uniqueProductIds = new Set(room.roomProductEntityList.map(product => product.productId));
          room.productTypeNum = uniqueProductIds.size;

          // 计算商品总数量（排除已删除的商品）
          room.productCount = room.roomProductEntityList.reduce((total, product) => {
            return product.isDel !== 1 ? total + product.count : total;
          }, 0);
        }
      });

      this.setData({
        programme
      });
      app.globalData.selectedProducts = [];
    }

    console.log("programme", this.data.programme);

    this.productTotalQuantity();
    this.defaultProductState();
  },

  //切换房间
  handleCustomTab(event) {
    const tid = event.currentTarget.dataset.tid;
    this.setData({
      tabs: tid
    });

    const {
      programme
    } = this.data;
    if (!programme || !programme.roomEntityList) {
      console.error("programme 或 roomEntityList 未定义");
      return;
    }
    programme.roomEntityList.forEach(room => {
      if (room.roomProductEntityList && room.roomProductEntityList.length > 0) {
        if (room.tid === tid) {
          room.roomProductEntityList.forEach((product, index) => {
            if (index < 20) {
              product.isShow = 0;
            } else {
              product.isShow = 1;
            }
          });
        } else {
          room.roomProductEntityList.forEach(product => {
            product.isShow = 1;
          });
        }
      }
    });

    // this.updateDiscounts()
    this.setData({
      programme: programme,
    });
    this.defaultProductState()
  },


  // 更新折扣商品
  updateDiscounts() {
    const {
      programme,
      customProductPrice
    } = this.data;
    console.log("更新折扣商品", this.data.programme);

    const discountPdt = programme.priceDiscountPdt !== null ? programme.priceDiscountPdt / 10 : null;
    const discountSev = programme.priceDiscountSev !== null ? programme.priceDiscountSev / 10 : null;

    programme.roomEntityList.forEach(room => {
      if (room.isDel !== 1) {
        room.roomProductEntityList.forEach(product => {
          if (product.isDel !== 1) {

            // 判断 priceModel 是 1 还是 2
            if (programme.priceModel == 1) {
              // 价格模型 1: 直接按折扣计算
              product.productPrice = product.oldProductPrice.toFixed(2);
              product.installationPrice = product.oldInstallationPrice.toFixed(2);
              product.serviceFee = product.oldServiceFee.toFixed(2);
              product.debuggingPrice = product.oldDebuggingPrice.toFixed(2);
              if (discountPdt !== null) {
                product.productPrice = (product.oldProductPrice * discountPdt).toFixed(2);
              }
              if (discountSev !== null) {
                product.installationPrice = (product.oldInstallationPrice * discountSev).toFixed(2);
                product.serviceFee = (product.oldServiceFee * discountSev).toFixed(2);
                product.debuggingPrice = (product.oldDebuggingPrice * discountSev).toFixed(2);
              }
            } else if (programme.priceModel == 2) {
              // 价格模型 2: 先匹配 customProductPrice
              console.log("@@@@@@@@@@@@");
              const customProduct = customProductPrice.find(cp => cp.productId === product.productId);
              if (customProduct) {
                // 替换为 customProductPrice 中的价格
                product.productPrice = customProduct.productPrice;
                product.installationPrice = customProduct.installationPrice;
                product.serviceFee = customProduct.serviceFee;
                product.debuggingPrice = customProduct.debuggingPrice;
              }
              console.log("customProduct+++++++++++++", customProduct);
              // 进行折扣计算
              if (discountPdt !== null) {
                product.productPrice = (Number(product.productPrice) * discountPdt).toFixed(2);
              }
              if (discountSev !== null) {
                product.installationPrice = (Number(product.installationPrice) * discountSev).toFixed(2);
                product.serviceFee = (Number(product.serviceFee) * discountSev).toFixed(2);
                product.debuggingPrice = (Number(product.debuggingPrice) * discountSev).toFixed(2);
              }
            }
          }
        });
      }
    });

    this.setData({
      programme
    });
    console.log("折扣商品价格已更新", programme);
  },

  // 获取用户选择的房间
  // handleConfirm: function () {
  //   this.setData({
  //     tabsRoom: app.globalData.roomList.rooms,
  //     roomList: app.globalData.roomList,
  //     tabs: app.globalData.roomList.rooms[0].tid,
  //   });

  //   console.log("app.globalData.roomList", this.data.tabsRoom);
  //   console.log("app.globalData.roomList", app.globalData.roomList);
  // },


  // 安装位置的选择
  locationChange(event) {
    const selectedLocationCode = event.detail;
    const selectedLocationObj = this.data.allLocation.find(location => location.id === selectedLocationCode);
    const {
      currentSplitIndex,
      currentRoomId,
      programme
    } = this.data;

    const updatedTabsRoom = programme.roomEntityList.map(room => {
      if (room.tid == currentRoomId) {
        return {
          ...room,
          roomProductEntityList: room.roomProductEntityList.map(product => {
            if (product.pid === currentSplitIndex) {
              return {
                ...product,
                productLocation: selectedLocationObj ? {
                  ...selectedLocationObj
                } : null,
                locationId: selectedLocationCode
              };
            }
            return product;
          })
        };
      }
      return room;
    });

    this.setData({
      "programme.roomEntityList": updatedTabsRoom,
      locationRadio: selectedLocationCode,
      showPosition: false
    });
    console.log("安装位置的选择", this.data.programme);
  },


  // 显示位置选择弹框
  showPositionChange(event) {
    console.log("显示位置选择弹框", this.data.programme);
    console.log("this.data.allLocation", this.data.allLocation);
    console.log("event", event);

    const pid = event.currentTarget.dataset.pid;
    const roomId = event.currentTarget.dataset.tid;
    const {
      programme
    } = this.data;

    let currentRoom = programme.roomEntityList.find(room => room.tid == roomId);
    if (currentRoom) {
      let currentProduct = currentRoom.roomProductEntityList.find(product => product.pid == pid);
      if (currentProduct) {
        const roomLocationCodes = currentRoom.roomLocation.split(",").map(code => Number(code)); // 将元素转换为数字
        console.log("roomLocationCodes", roomLocationCodes);

        const locationList = this.data.allLocation.filter(location =>
          roomLocationCodes.includes(location.id) // 直接比较数字
        ).map(location => ({
          ...location,
          checked: currentProduct.locationId == location.id
        }));

        console.log("locationList", locationList);
        this.setData({
          showPosition: true,
          locationList: locationList,
          currentSplitIndex: pid,
          currentRoomId: roomId,
          locationRadio: String(currentProduct.locationId) || ''
        });
        console.log("locationRadio", this.data.locationRadio);
      } else {
        console.error("未找到对应的商品");
      }
    } else {
      console.error("未找到对应的房间");
    }
  },

  //公共位置
  async getLocationAll() {
    try {
      const res = await request({
        url: indexApi.getProductLocationAllApi(),
        data: {}
      });

      const updatedLocationAll = res.data.records.map(item => ({
        ...item,
        checked: false
      }));
      this.setData({
        PublicLocations: updatedLocationAll
      })
      console.log("安装公共位置", this.data.PublicLocations);
      this.getMyLocations()
    } catch (error) {
      console.error("Error:", error);
    }
  },

  // 获取私有位置
  async getMyLocations() {
    const pageNum = 1
    const pageSize = 1000
    try {
      const res = await request({
        url: indexApi.getMyLocationsApi(pageNum, pageSize),
        data: {}
      });

      const updatedLocationAll = res.data.records.map(item => ({
        ...item,
        checked: false
      }));
      this.setData({
        MyLocations: updatedLocationAll
      })
      this.mergeLocations();
      console.log("私有位置", this.data.MyLocations);
    } catch (error) {
      console.error("Error:", error);
    }
  },

  //合并私有位置和公共位置
  mergeLocations() {
    const allLocation = [...this.data.MyLocations, ...this.data.PublicLocations];
    this.setData({
      allLocation: allLocation
    });
    console.log("合并后的所有位置", this.data.allLocation);
  },


  // // 在页面初始化时获取全部位置数据
  // async getLocationAll() {
  //   console.log("地址接口");
  //   let a = 'INS_POSITION';
  //   try {
  //     const res = await request({
  //       url: indexApi.getSysDicApi(a),
  //       data: {}
  //     });
  //     const updatedLocationAll = res.data.map(item => ({
  //       ...item,
  //       checked: false
  //     }));
  //     this.setData({
  //       allLocation: updatedLocationAll
  //     });
  //   } catch (error) {
  //     console.error("Error:", error);
  //   }
  // },

  // 拆分合并
  toggleMergeSplit(event) {
    const {
      programme,
      tabs
    } = this.data;
    const currentRoom = programme.roomEntityList.find(room => room.tid === tabs);
    if (this.data.isMerge == false) {
      this.productLocationSort(currentRoom.roomProductEntityList);
    }
    this.setData({
      isExpanded: false,
      isMerge: !this.data.isMerge,
      programme,
    });
  },

  //加载商品
  loadMoreProducts() {
    const {
      programme,
      tabs
    } = this.data;
    const room = programme.roomEntityList.find(room => room.tid === tabs);
    if (!room) return;
    const currentlyDisplayed = room.roomProductEntityList.filter(product => product.isShow === 0).length;
    const nextBatchStart = currentlyDisplayed;
    const nextBatchEnd = nextBatchStart + 20;
    room.roomProductEntityList.forEach((product, index) => {
      if (index >= nextBatchStart && index < nextBatchEnd) {
        product.isShow = 0;
      }
    });
    this.setData({
      programme
    });
    console.log("加载++++++++++++++++++");
    this.productLocationSort(this.data.programme)
  },

  // 商品位置排序
  productLocationSort(roomProductEntityList) {
    return roomProductEntityList.sort((a, b) => {
      const aLocationId = a.locationId ?? Infinity;
      const bLocationId = b.locationId ?? Infinity;
      if (aLocationId > bLocationId) return 1;
      if (aLocationId < bLocationId) return -1;
      return 0;
    });
  },

  bindPickerProperty(event) {
    const PropertyIndex = event.detail.value
    const selectedPropertyTitle = this.data.ProductProperty[PropertyIndex].title;
    const propertyId = this.data.ProductProperty[PropertyIndex].id;
    this.setData({
      selectedProperty: selectedPropertyTitle,
      propertyId: propertyId
    })
  },



  // 默认操作状态
  defaultProductState() {
    this.setData({
      checkedAll: false,
      showImageUrl: true,
      isExpanded: false,
      isEdit: false,
      isDelete: false,
      isSelectAll: false,
      isSplit: true,
      isCommodity: true,
      isMerge: false
    })
  },

  // 减少商品数量
  reduce(event) {
    const productId = event.currentTarget.dataset.productid;
    const {
      programme,
      tabs
    } = this.data;
    const currentRoom = programme.roomEntityList.find(room => room.tid === tabs);
    const productIndex = currentRoom.roomProductList.findIndex(
      product => product.productId === productId
    );
    if (productIndex !== -1) {
      if (currentRoom.roomProductList[productIndex].count > 1) {
        currentRoom.roomProductList[productIndex].count -= 1;
        const removeIndex = currentRoom.roomProductEntityList.findIndex(
          product => product.productId === productId && !product.locationId && product.isDel === 0
        );
        if (removeIndex !== -1) {
          const productToRemove = currentRoom.roomProductEntityList[removeIndex];
          if (productToRemove.id) {
            currentRoom.roomProductEntityList[removeIndex].isDel = 1;
          } else {
            currentRoom.roomProductEntityList.splice(removeIndex, 1);
          }
        } else {
          const markDelIndex = currentRoom.roomProductEntityList.findIndex(
            product => product.productId === productId && product.isDel === 0
          );
          if (markDelIndex !== -1) {
            currentRoom.roomProductEntityList[markDelIndex].isDel = 1;
          }
        }
      }
    }
    currentRoom.productCount = currentRoom.roomProductEntityList.reduce(
      (total, product) => total + (product.isDel === 0 ? product.count : 0),
      0
    );
    this.setData({
      programme
    });
    this.productTotalQuantity();
  },


  // 增加商品数量
  add(event) {
    const productId = event.currentTarget.dataset.productid;
    const {
      programme,
      tabs
    } = this.data;
    const generateUniquePid = () => `${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    const currentRoom = programme.roomEntityList.find(room => room.tid === tabs);
    const productIndex = currentRoom.roomProductList.findIndex(
      product => product.productId === productId
    );
    if (productIndex !== -1) {
      currentRoom.roomProductList[productIndex].count += 1;
      let newProduct = {
        ...currentRoom.roomProductList[productIndex]
      };
      if (newProduct.id) {
        delete newProduct.id;
      }
      delete newProduct.location;
      delete newProduct.locationId;
      console.log("currentRoom.roomProductEntityList", currentRoom.roomProductEntityList);
      newProduct = {
        ...newProduct,
        count: 1,
        splitIndex: currentRoom.roomProductEntityList.length,
        isDel: 0,
        isShow: 0,
        pid: generateUniquePid()
      };
      currentRoom.roomProductEntityList.push(newProduct);

    }
    console.log("currentRoom.productCount", currentRoom.productCount);
    console.log("currentRoom.roomProductEntityList", currentRoom.roomProductEntityList);

    currentRoom.productCount = currentRoom.roomProductEntityList.reduce(
      (total, product) => total + (product.isDel === 0 ? product.count : 0),
      0
    );
    this.setData({
      programme
    });
    console.log("点击加商品", this.data.programme);

    this.productTotalQuantity();
  },


  // 输入商品数量
  onInputChange(event) {
    const value = parseInt(event.detail.value, 10);
    this.setData({
      tempProductCount: isNaN(value) ? 0 : value,
    });
  },

  // 商品数量输入的弹框
  clickInput(event) {
    const currentProductId = event.currentTarget.dataset.productid;
    const {
      programme,
      tabs
    } = this.data;
    const currentRoom = programme.roomEntityList.find(room => room.tid === tabs);
    const productIndex = currentRoom.roomProductList.findIndex(product => product.productId == currentProductId);
    if (productIndex !== -1) {
      const currentProductCount = currentRoom.roomProductList[productIndex].count;
      this.setData({
        isDialogVisible: true,
        currentProductId,
        tempProductCount: currentProductCount,
      });
    }
  },

  // 确认输入的数量并关闭弹框
  onDialogConfirm() {
    const {
      programme,
      tabs,
      tempProductCount,
      currentProductId
    } = this.data;
    const generateUniquePid = () => `${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    const currentRoom = programme.roomEntityList.find(room => room.tid === tabs);
    const productIndex = currentRoom.roomProductList.findIndex(product => product.productId == currentProductId);
    if (productIndex !== -1) {
      const oldCount = currentRoom.roomProductList[productIndex].count;
      currentRoom.roomProductList[productIndex].count = tempProductCount;
      const difference = tempProductCount - oldCount;
      if (difference > 0) {
        for (let i = 0; i < difference; i++) {
          let newProduct = {
            ...currentRoom.roomProductList[productIndex]
          };
          delete newProduct.id;
          delete newProduct.location;
          delete newProduct.locationId;
          newProduct = {
            ...newProduct,
            count: 1,
            splitIndex: currentRoom.roomProductEntityList.length,
            isDel: 0,
            isShow: 1,
            pid: generateUniquePid()
          };
          currentRoom.roomProductEntityList.push(newProduct);
        }
      } else if (difference < 0) {
        let remainingDifference = Math.abs(difference);
        while (remainingDifference > 0) {
          let removeIndex = currentRoom.roomProductEntityList.findIndex(
            product => product.productId === currentProductId && !product.locationId && product.isDel === 0
          );
          if (removeIndex !== -1) {
            const productToRemove = currentRoom.roomProductEntityList[removeIndex];
            if (productToRemove.id) {
              currentRoom.roomProductEntityList[removeIndex].isDel = 1;
            } else {
              currentRoom.roomProductEntityList.splice(removeIndex, 1);
            }
            remainingDifference--;
            const nonDeletedProductCount = currentRoom.roomProductEntityList.filter(
              product => product.productId === currentProductId && product.isDel === 0
            ).length;

          } else {
            break;
          }
        }
        while (remainingDifference > 0) {
          const markDelIndex = currentRoom.roomProductEntityList.findIndex(
            product => product.productId === currentProductId && product.isDel === 0
          );
          if (markDelIndex !== -1) {
            currentRoom.roomProductEntityList[markDelIndex].isDel = 1;
            remainingDifference--;
          } else {
            break;
          }
        }
      }

      currentRoom.productCount = currentRoom.roomProductEntityList.reduce(
        (total, product) => total + (product.isDel === 0 ? product.count : 0),
        0
      );
      for (let i = 0; i < Math.min(currentRoom.roomProductEntityList.length, 20); i++) {
        currentRoom.roomProductEntityList[i].isShow = 0;
      }
      this.setData({
        isDialogVisible: false,
        programme
      });
    }
    this.productTotalQuantity();
  },


  toProductList() {
    const {
      programme
    } = this.data
    if (this.data.serviceType == null) {
      Toast('请先选择类目');
    } else {
      const serviceType = this.data.serviceType;
      console.log("serviceType", serviceType);
      const serviceTypeStr = encodeURIComponent(JSON.stringify(serviceType));
      const fromPage = 1;
      wx.setStorageSync('programmeData', programme);
      wx.navigateTo({
        url: `/packageOrder/pages/product/index?serviceTypeName=${serviceTypeStr}&fromPage=${fromPage}&programme=${programme}`,
      });
    }
  },

  //获取价格体系
  async getCustomPrice() {
    try {
      const res = await request({
        url: indexApi.getCustomPriceApi(),
        data: {}
      });
      console.log("-------------------------", res.data);
      if (res.data !== null) {
        this.setData({
          customPrice: res.data[0]
        })
        console.log("获取价格体系", this.data.customPrice);
      }

      this.getCustomPriceItems()
    } catch (error) {
      console.error("Error:", error);
    }
  },

  //获取价格体系商品列表
  async getCustomPriceItems() {
    const id = this.data.customPrice.id;
    const pageNum = 1
    const pageSize = 1000
    try {
      const res = await request({
        url: indexApi.getCustomPriceItemsApi(pageNum, pageSize, id),
        data: {}
      });
      this.setData({
          customProductPrice: res.data.records
        },
        // () => {
        //   this.replaceProduct()
        // }
      )

      console.log("获取价格体系商品列表", this.data.customProductPrice);
      console.log("房间下的商品", this.data.programme);
    } catch (error) {
      console.error("Error:", error);
    }
  },

  // 修改商品价格


  // 单个折叠面板
  handleDropDown(event) {
    console.log("programme", this.data.programme);
    const pid = event.currentTarget.dataset.pid;
    const {
      isMerge,
      programme,
      tabs
    } = this.data;
    const currentRoom = programme.roomEntityList.find(room => room.tid === tabs);
    const targetArray = isMerge ? currentRoom.roomProductList : currentRoom.roomProductEntityList;
    const product = targetArray.find(item => item.pid === pid);
    if (product) {
      this.setData({
        [`expandedProducts.${pid}`]: !this.data.expandedProducts[pid]
      });
      this.checkAllExpanded();
    }
  },
  checkAllExpanded() {
    let allExpanded = true;
    let allCollapsed = true;
    const {
      isMerge,
      programme
    } = this.data;
    programme.roomEntityList.forEach(room => {
      const targetArray = isMerge ? room.roomProductList : room.roomProductEntityList;
      targetArray.forEach(product => {
        const pid = product.pid;
        if (this.data.expandedProducts[pid]) {
          allCollapsed = false;
        } else {
          allExpanded = false;
        }
      });
    });
    this.setData({
      isAllExpanded: allExpanded,
      isExpanded: allExpanded
    });
    if (!allExpanded && allCollapsed) {
      this.setData({
        isAllExpanded: false,
        isExpanded: false
      });
    }
  },

  toggleExpandAll(event) {
    const tid = event.currentTarget.dataset.tid;
    const {
      isMerge,
      programme
    } = this.data;
    const room = programme.roomEntityList.find(room => room.tid == tid);
    if (room) {
      const isAllExpanded = !this.data.isAllExpanded;
      const expandedProducts = {};
      const targetArray = isMerge ? room.roomProductList : room.roomProductEntityList;
      targetArray.forEach(product => {
        const pid = product.pid;
        expandedProducts[pid] = isAllExpanded;
      });
      this.setData({
        expandedProducts,
        isAllExpanded,
        isExpanded: isAllExpanded
      });
    } else {
      Toast('没有可展开的商品');
    }
  },


  // 点击编辑
  handleImageUrl(event) {
    const {
      isMerge
    } = this.data;
    const tid = event.currentTarget.dataset.tid;
    const room = this.data.programme.roomEntityList.find(room => room.tid == tid);
    if (room && room.roomProductEntityList.length > 0) {
      this.setData({
        showImageUrl: !this.data.showImageUrl,
        isEdit: !this.data.isEdit,
        isDelete: !this.data.isDelete,
        isSelectAll: !this.data.isSelectAll,
        isCommodity: !this.data.isCommodity,
        isSplit: !this.data.isSplit,
        sanPopup: false,
        squareCheckedProducts: {},
        checkedAll: false
      });
    } else {
      Toast('没有可编辑的商品');
    }
  },

  // 单选
  squareChange(e) {
    const pid = e.currentTarget.dataset.pid;
    const checked = e.detail;
    const {
      isMerge,
      programme,
      tabs
    } = this.data;
    const currentRoom = programme.roomEntityList.find(room => room.tid === tabs);
    const targetArray = isMerge ? currentRoom.roomProductList : currentRoom.roomProductEntityList;
    const targetProduct = targetArray.find(item => item.pid === pid);

    if (targetProduct && (isMerge || targetProduct.isDel !== 1)) {
      const updatedProducts = {
        ...this.data.squareCheckedProducts,
        [pid]: checked
      };
      this.setData({
        squareCheckedProducts: updatedProducts
      }, () => {
        this.updateCheckAllStatus();
      });
    }
  },


  // 全选
  handleCheckAll(e) {
    const checkedAll = e.detail;
    const roomId = e.currentTarget.dataset.tid;
    const {
      isMerge,
      programme
    } = this.data;
    const currentRoom = programme.roomEntityList.find(room => room.tid === roomId);
    const targetArray = isMerge ? currentRoom.roomProductList : currentRoom.roomProductEntityList;
    const squareCheckedProducts = {};
    targetArray.forEach(item => {
      if (isMerge || item.isDel !== 1) {
        squareCheckedProducts[item.pid] = checkedAll;
      }
    });
    this.setData({
      checkedAll,
      squareCheckedProducts
    });
  },
  updateCheckAllStatus() {
    const {
      isMerge,
      programme,
      tabs
    } = this.data;
    const currentRoom = programme.roomEntityList.find(room => room.tid === tabs);
    const targetArray = isMerge ? currentRoom.roomProductList : currentRoom.roomProductEntityList;
    const validItems = targetArray.filter(item => isMerge || item.isDel !== 1);
    const allChecked = validItems.length > 0 && validItems.every(item => this.data.squareCheckedProducts[item.pid]);
    this.setData({
      checkedAll: allChecked
    });
  },

  // 删除
  handleDelete() {
    const hasCheckedProduct = Object.values(this.data.squareCheckedProducts).some(value => value);
    if (!hasCheckedProduct) {
      Toast('您还没有选择商品');
      return;
    }
    Dialog.confirm({
      title: '确认删除吗',
    }).then(() => {
      const {
        programme,
        tabs,
        isMerge
      } = this.data;
      const currentRoom = programme.roomEntityList.find(room => room.tid === tabs);
      const checkedPids = Object.keys(this.data.squareCheckedProducts).filter(pid => this.data.squareCheckedProducts[pid]);
      if (isMerge) {
        checkedPids.forEach(pid => {
          const productListIndex = currentRoom.roomProductList.findIndex(p => p.pid === pid);
          if (productListIndex !== -1) {
            const productId = currentRoom.roomProductList[productListIndex].productId;
            currentRoom.roomProductList.splice(productListIndex, 1);
            currentRoom.roomProductEntityList = currentRoom.roomProductEntityList.filter(entity => {
              if (entity.productId === productId) {
                if (entity.id) {
                  entity.isDel = 1;
                  return true;
                }
                return false;
              }
              return true;
            });
          }
        });
      } else {
        checkedPids.forEach(pid => {
          const productIndex = currentRoom.roomProductEntityList.findIndex(p => p.pid === pid);
          if (productIndex !== -1) {
            const product = currentRoom.roomProductEntityList[productIndex];
            if (product.id) {
              product.isDel = 1;
            } else {
              currentRoom.roomProductEntityList.splice(productIndex, 1);
            }
            const productListIndex = currentRoom.roomProductList.findIndex(p => p.productId === product.productId);
            if (productListIndex !== -1) {
              currentRoom.roomProductList[productListIndex].count -= 1;
              const remainingCount = currentRoom.roomProductEntityList.filter(entity => entity.productId === product.productId && entity.isDel !== 1).length;
              if (remainingCount === 0) {
                currentRoom.roomProductList.splice(productListIndex, 1);
              }
            }
          }
        });
      }
      const activeProducts = currentRoom.roomProductEntityList.filter(product => product.isDel !== 1);
      const uniqueProductIds = new Set(activeProducts.map(product => product.productId));
      currentRoom.productTypeNum = uniqueProductIds.size;
      currentRoom.productCount = activeProducts.reduce((total, product) => total + product.count, 0);
      if (activeProducts.length < 1) {
        this.setData({
          programme: this.data.programme,
          squareCheckedProducts: {},
          checkedAll: false,
          showImageUrl: false,
          isExpanded: false,
          isEdit: !this.data.isEdit,
          isDelete: !this.data.isEdit,
          isSelectAll: !this.data.isSelectAll,
          isCommodity: !this.data.isCommodity,
          isSplit: !this.data.isSplit,
        });
      } else {
        this.setData({
          programme: this.data.programme,
          squareCheckedProducts: {},
          checkedAll: false,
        });
      }

      console.log("pro", this.data.programme);
      this.productTotalQuantity()
    }).catch(() => {});
  },

  inputChange: function (e) {
    this.setData({
      keyword: e.detail.value
    });
  },
  // 搜索按钮点击事件
  search: function () {
    const keyword = this.data.keyword;
  },

  //工时
  async getSysConfigInfo() {
    try {
      const res = await request({
        url: indexApi.getSysConfigInfoApi(),
        data: {}
      });
      console.log("工时++++++++", res.data);
      this.setData({
        workHours: Number(res.data.data.SERVICE_HOURS_DAY),
        workPrice: Number(res.data.data.SERVICE_HOURS_PRICE)
      })

    } catch (error) {
      console.error("Error:", error);
    }
  },

  // 服务统计商品数量等
  productTotalQuantity() {
    console.log("this.data.programme", this.data.programme);
    const {
      workHours,
      workPrice
    } = this.data
    const programme = this.data.programme;
    let newProductCount = 0;
    let newProductPrice = 0;
    let newDebugPrice = 0;
    let newServicePrice = 0;
    let newServiceDuration = 0
    // let totalServiceFee=0

    programme.roomEntityList.forEach(room => {
      room.roomProductEntityList.forEach(product => {
        if (product.isDel !== 1) {
          newProductCount += 1;
          newProductPrice += Number(product.productPrice);
          newDebugPrice += Number(product.debuggingPrice) + Number(product.installationPrice);
          newServicePrice += Number(product.serviceFee)
          newServiceDuration += Number(product.serviceDuration)
        }
      });
    });

    programme.roomEntityList.forEach(room => {
      room.roomProductList.forEach(product => {
        if (product.isDel !== 1) {
          product.totalProductPrice=(product.productPrice*product.count).toFixed(2);
          product.totalDebuggingPrice=(product.debuggingPrice*product.count).toFixed(2);
          product.totalInstallationPrice=(product.installationPrice*product.count).toFixed(2);
          product.totalServiceDuration=(product.serviceDuration*product.count).toFixed(2);
        }
      });
    });

    console.log("programme.totalPrice", newProductPrice);
    programme.productCount = newProductCount;

    programme.totalPrice = newProductPrice.toFixed(2);
    programme.debugPrice = newDebugPrice.toFixed(2);
    programme.servicePrice = newServicePrice.toFixed(2);
    programme.serviceDuration = newServiceDuration.toFixed(2)
    const serviceFeeMath = Math.ceil(newServiceDuration.toFixed(2) / workHours)
    programme.serviceFee = (serviceFeeMath * workPrice).toFixed(2)
    programme.programmeTotalPrice = (newProductPrice + newDebugPrice + serviceFeeMath * workPrice).toFixed(2);


    this.setData({
      programme
    });


    console.log("++++++++++++++++++++++++==============",this.data.programme);
    this.productTotalCategory();
  },

  // 计算产品种类数量
  productTotalCategory() {
    const programme = this.data.programme;
    const uniqueProductIds = new Set();
    programme.roomEntityList.forEach(room => {
      room.roomProductList.forEach(product => {
        uniqueProductIds.add(product.productId);
      });
    });
    programme.productTypeNum = uniqueProductIds.size;
    this.setData({
      programme
    });
    console.log("计算产品种类数量", this.data.programme);
  },

  //日期
  showDatetimePicker() {
    this.setData({
      showTime: true
    });
  },
  onConfirm(event) {
    const timestamp = event.detail;
    const date = new Date(timestamp);
    const formattedDate = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
    this.setData({
      showTime: false,
      selectedDate: formattedDate
    });
  },
  onCancel() {
    this.setData({
      showTime: false
    });
  },
  timeClose() {
    this.setData({
      showTime: false
    });
  },

  //上传图片
  afterRead(event) {
    const {
      file
    } = event.detail;
    this.uploadFile(file);
  },

  // 文件超出大小限制处理函数
  onOversize(event) {
    wx.showToast({
      title: '文件大小超出限制',
      icon: 'none'
    });
  },

  // 上传图片
  async uploadFile(file) {
    try {
      const uploadTask = wx.uploadFile({
        url: indexApi.upLoadApi(),
        header: {
          "Content-Type": "multipart/form-data"
        },
        filePath: file.url,
        name: 'file',
        formData: {

        },
        success: (res) => {
          const data = JSON.parse(res.data);
          this.setData({
            fileList: [...this.data.fileList, file]
          });
        },
        fail: (err) => {
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          });
        }
      });
    } catch (error) {
      console.error("Error:", error);
    }
  },

  // 删除图片
  onDelete(event) {
    const {
      index
    } = event.detail;
    const {
      fileList
    } = this.data;
    fileList.splice(index, 1);
    this.setData({
      fileList
    });
  },

  // 显示类目弹框
  showCategory() {
    this.setData({
      showpopup: true,
      three: false
    })
    this.getSeverAll()
  },
  onClose() {
    this.setData({
      showpopup: false,
      addressPop: false,
      three: true,
      isDialogVisible: false,
    });
  },
  closePosition() {
    this.setData({
      showPosition: false,

    });
  },
  showPopup() {
    this.setData({
      showpopup: true
    });
  },
  //选择类目
  navigateToServePage(event) {
    const serviceType = event.currentTarget.dataset.category
    const serviceTypeId = event.currentTarget.dataset.category.serviceTypeId
    this.setData({
      showpopup: false,
      serviceTypeName: serviceType.serviceTypeName,
      serviceType: serviceType,
      serviceTypeId,
      three: true
    });
    app.globalData.serviceType = serviceType
  },

  //显示配置弹窗
  MoreConfigurations() {
    this.setData({
      showAllocation: true,
      three: false
    })
  },
  moreClose() {
    this.setData({
      showAllocation: false,
      three: true
    });
  },
  // 小弹框
  handleSan: function () {
    this.setData({
      sanPopup: true
    });
  },


  handleTapOutside: function (event) {
    if (event.target.dataset.sanPopup !== 'true' && event.target.dataset.showRoomPopup !== 'true') {
      this.setData({
        sanPopup: false,
        showRoomPopup: false
      });
    }
  },

  //  房间弹框
  handleRoom() {
    this.setData({
      sanPopup: false
    }, () => {
      this.setData({
        showRoomPopup: true,
        three: false,
      }, () => {});
    });
  },

  //跳到户型页面
  toHouseType() {
    const app = getApp();
    const programme = this.data.programme;
    app.globalData.programme = programme;
    wx.navigateTo({
      url: `/packageOrder/pages/houseType/index?programme=${encodeURIComponent(JSON.stringify(programme))}`,
    });
  },

  roomClose() {
    this.setData({
      showRoomPopup: false
    });
  },



  //关闭房间弹框
  handleCloseRoom() {
    this.setData({
      showRoomPopup: false,
      three: true,
    })
  },

  //二期服务类目
  async getSeverAll() {
    try {
      const res = await request({
        url: indexApi.severApi(),
        data: {}
      });
      this.setData({
        menuList: res.data
      })
    } catch (error) {
      console.error("Error:", error);
    }
  },

  //一期服务类目
  async getOneSeverAll() {
    try {
      const res = await request({
        url: indexApi.severApi(),
        data: {}
      });
      this.setData({
        serviceTypeName: res.data[2].serviceTypeName,
        serviceTypeId: res.data[2].serviceTypeId,
        serviceType: res.data[2],
        "programme.serviceTypeId": res.data[2].serviceTypeId,
      })
      app.globalData.serviceType = res.data[2]
    } catch (error) {
      console.error("Error:", error);
    }
  },

  // 地址弹框
  clickIcon() {
    this.setData({
      addressPop: true
    })
    const child = this.selectComponent('#myChild');
    child.getAddress();
  },
  addressClose() {
    this.setData({
      addressPop: false
    })
  },
  addressPopClose(event) {
    const {
      selectedAddressId,
      selectedAddress
    } = event.detail;
    this.setData({
      addressPop: false,
      selectedAddressId,
      selectedAddress
    })
  },

  enterPopup() {
    setTimeout(() => {
      const addressPopup = this.selectComponent('#myAddressPopup');
      if (addressPopup) {
        addressPopup.getAddress();
      } else {
        console.error('Failed to get addressPopup component');
      }
    }, 10);
  },

  // 检查 token 的函数
  checkToken() {
    try {
      const token = wx.getStorageSync('token');
      if (token) {
        this.setData({
          hasToken: true
        });
        console.log("检查 token登录", this.data.hasToken);
      } else {
        this.showLoginDialog();
      }
    } catch (e) {
      console.error('获取 token 失败：', e);
      // this.showLoginDialog();
    }
  },

  showLoginDialog: function () {
    wx.showModal({
      title: '登录提示',
      content: '您还未登录，请登录以继续使用',
      showCancel: false,
      success(res) {
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/login/index',
          })
        }
      }
    });
  },


  //获取整个订单数据,展示到支付页面
  async getOrderByOrder(getOrderId) {
    const orderId = getOrderId
    const reqTemplate = {
      orderId: orderId
    }
    try {
      const res = await request({
        url: indexApi.getByOrderId(),
        method: "POST",
        data: reqTemplate
      });
      const orderString = encodeURIComponent(JSON.stringify(res.data));
      wx.navigateTo({
        url: `/packageOrder/pages/orderDetails/index?order=${orderString}`
      });
    } catch (error) {
      console.error("Error:", error);
    }
  },




  // 分享给朋友
  onShareAppMessage: function () {
    return {
      title: '方案报价',
      path: '/pages/quick/index',

    };
  },

  // 分享到朋友圈
  onShareTimeline: function () {
    return {
      title: '方案报价',
      query: ''
    };
  },

  // TabBar 切换到 quick 页面时的处理
  onTabItemTap(item) {
    this.checkToken();
  }
});